package com.whfc.cncit.helmet.codec;


import com.whfc.cncit.constant.CncitConst;
import com.whfc.cncit.entity.CncitMsg;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/10/24 14:57
 */
public class CncitMsgEncoder extends MessageToMessageEncoder<CncitMsg> {

    private Logger logger = LoggerFactory.getLogger(CncitMsgEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, CncitMsg msg, List<Object> out) throws Exception {


        String data = null;
        String cmd = msg.getCmd();
        CncitMsgCodec codec = CncitMsgCodecFactory.create(cmd);
        if (codec != null) {
            data = codec.encode(msg);
        }
        if (!StringUtils.isEmpty(data)) {
            ByteBuf buf = Unpooled.buffer(data.length() + 1);
            if (cmd.equals(CncitConst.DW_CMD_PS)){
                buf.writeCharSequence(data, CncitConst.GBK);
            }else {
                buf.writeCharSequence(data, CncitConst.UTF8);
            }
            buf.writeByte(CncitConst.END_DW);
            logger.info("发送数据:{}", ByteBufUtil.prettyHexDump(buf));
            out.add(buf);
        }
    }
}
